import os
import sys
import time

import requests

import cachetools.func
from apis import owhat, taoba
from flask import Flask, abort, request, send_file, send_from_directory
from flask_cors import CORS
from flask_limiter import Limiter
from flask_limiter.util import get_remote_address

SOURCE_ROOT = os.path.abspath(os.path.dirname(__file__))
app = Flask('pkb48')
CORS(app)
limiter = Limiter(app, key_func=get_remote_address, default_limits=[])


@app.route('/')
def index():
    try:
        return send_file(os.path.join(SOURCE_ROOT, 'dist', 'index.html'))
    except IOError:
        abort(404)


@app.route('/<path:path>')
def static_files(path):
    return send_from_directory(os.path.join(SOURCE_ROOT, 'dist'), path)


@app.route('/fund/<typ>/<ID>')
@limiter.limit("60/second")
@cachetools.func.ttl_cache(ttl=10)
def fund_info(typ, ID):
    if typ == 'taoba':
        return taoba.get_fund_info(ID)
    elif typ == 'owhat':
        return owhat.get_fund_info(ID)
    else:
        abort(400)


if __name__ == "__main__":
    port = 8000
    if len(sys.argv) > 1:
        port = int(sys.argv[1])
    if os.getenv('DEBUG'):
        app.run(host="0.0.0.0", port=port, debug=True, use_reloader=True)
    else:
        # app.run(port=8000, threaded=True, processes=4)
        app.run(host="0.0.0.0", port=port, threaded=True)
